<template>
  <div class="container">
    <h1>新建车辆</h1>
    <hr style="border: 1px solid rgb(240, 240, 240)" />
    <span>基础信息</span>
    <div class="body">
      <!-- 车牌号 -->
      <div class="input">
        <div class="input-left">
          <span>车牌号</span>
        </div>
        <div class="input-right">
          <el-input v-model="car_id" placeholder="请输入" />
        </div>
      </div>

      <!-- 车辆品牌 -->
      <div class="input">
        <div class="input-left">
          <span>车辆品牌</span>
        </div>
        <div class="input-right">
          <el-select v-model="car_brand" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 车辆型号 -->
      <div class="input">
        <div class="input-left">
          <span>车辆型号</span>
        </div>
        <div class="input-right">
          <el-input v-model="car_type" placeholder="请输入" />
        </div>
      </div>

      <!-- 车身颜色 -->
      <div class="input">
        <div class="input-left">
          <span>车身颜色</span>
        </div>
        <div class="input-right">
          <el-input v-model="car_color" placeholder="请输入" />
        </div>
      </div>

      <!-- 上传图片部分 -->
      <div class="input">
        <div class="input-left">
          <span>车辆图片</span>
        </div>
        <div class="input-righta">
          <el-upload
            class="upload-demo"
            action="http://localhost:8080/vehicleCar/upload"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
            :headers="uploadHeaders"
            :multiple="true"
            :file-list="fileList"
          />
        </div>
      </div>

      <!-- 持有人 -->
      <div class="input">
        <div class="input-left">
          <span>持有人</span>
        </div>
        <div class="input-right">
          <el-input v-model="holder" placeholder="请输入" />
        </div>
      </div>

      <!-- 备注 -->
      <div class="input">
        <div class="input-left">
          <span>备注</span>
        </div>
        <div class="input-right">
          <el-input v-model="remark" :rows="5" type="textarea" />
        </div>
      </div>

      <div style="margin: 2rem 0 2rem 12rem">
        <el-button type="primary" @click="submitVehicle">提交</el-button>
        <el-button type="default" @click="to('car/car')">返回</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import to from "@/utils/to.js";
import axios from "axios"; // 引入 axios 用于发送 HTTP 请求
import { ElMessage } from "element-plus"; // 引入 Element Plus 的消息提示
import { useRoute } from "vue-router";

// 定义表单数据
const car_id = ref("");
const car_brand = ref("");
const car_type = ref("");
const car_color = ref("");
const holder = ref("");
const remark = ref("");
const imageUrls = ref([]); // 存储上传的图片 URLs
const fileList = ref([]);

// 车辆品牌选项
const options = [
  { value: "品牌1", label: "品牌1" },
  { value: "品牌2", label: "品牌2" },
  { value: "品牌3", label: "品牌3" },
  { value: "品牌4", label: "品牌4" },
];

// 编辑标识
const isEdit = ref(false);

// 获取 URL 参数
const route = useRoute();
const id = route.params.id || route.query.id;

// 动态请求头
const uploadHeaders = computed(() => ({
  Authorization: localStorage.getItem("token"),
}));

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  if (response.code === 1) {
    ElMessage.success("图片上传成功!");
    const nginxUrl = `http://localhost/upload/${response.data
      .split("/")
      .pop()}`;
    imageUrls.value.push(nginxUrl);
    fileList.value.push({
      name: file.name,
      url: nginxUrl,
    });
  } else {
    ElMessage.error("图片上传失败!");
  }
};

// 上传失败回调
const handleUploadError = (error) => {
  ElMessage.error("图片上传失败!");
  console.error(error);
};

const handleRemove = (file, fileList) => {
  const urlToRemove = file.url; // 获取被删除图片的 URL
  // 从 imageUrls 中移除对应的 URL
  imageUrls.value = imageUrls.value.filter((url) => url !== urlToRemove);
  // 更新 fileList
  fileList.value = fileList; // fileList 已自动更新，无需额外处理
  ElMessage.success("图片删除成功!");
};

const handlePreview = (file) => {
  const imageUrl = file.url; // 获取图片的 URL
  if (imageUrl) {
    window.open(imageUrl, "_blank"); // 在新标签页打开图片
  } else {
    ElMessage.warning("图片无法预览");
  }
};


// 加载车辆数据（编辑时填充表单）
const fetchVehicleData = async () => {
  if (!id) return;

  try {
    const response = await axios.get(
      "http://localhost:8080/vehicleCar/selectById",
      {
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        params: { id },
      }
    );
    const data = response.data.data;
    if (data) {
      car_id.value = data.carNo;
      car_brand.value = data.brand;
      car_type.value = data.size;
      car_color.value = data.color;
      holder.value = data.owner;
      remark.value = data.notes;
      if (typeof data.images === "string") {
         const urls = data.images.split(",");
        imageUrls.value = urls; // 将字符串转为数组
        fileList.value = urls.map((url) => ({
              name: url.split("/").pop(), // 获取文件名
              url, // 保留完整的 URL
        })); // 更新文件列表
      } else {
        imageUrls.value = Array.isArray(data.images) ? data.images : [];
        fileList.value = Array.isArray(data.images)
          ? data.images.map((url) => ({ name: url.split("/").pop(), url }))
          : [];
      }
      isEdit.value = true; // 设置为编辑模式
      console.log(data);
    }
  } catch (error) {
    console.error("获取车辆数据失败", error);
    ElMessage.error("车辆数据加载失败");
  }
};

const submitVehicle = async () => {
  // 创建车辆数据对象
  const vehicleData = {
    vehicleCar: {
      id: id,
      carNo: car_id.value,
      brand: car_brand.value,
      size: car_type.value,
      color: car_color.value,
      owner: holder.value,
      notes: remark.value,
    },
    images: [...imageUrls.value], // 将响应式数组转换为普通数组
  };
  console.log(vehicleData);
  try {
    let response;
    if (isEdit.value) {
      const config = {
        url: "http://localhost:8080/vehicleCar/update",
        method: "PUT",
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        data: vehicleData,
      };

      response = await axios(config);
    } else {
      const config = {
        url: "http://localhost:8080/vehicleCar/add",
        method: "POST",
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        data: vehicleData,
      };

      response = await axios(config);
    }

    if (response.status === 200) {
      ElMessage.success("车辆添加成功!");

      setTimeout(() => {
        to("car/car");
      }, 2000);
    }
  } catch (error) {
    ElMessage.error("车辆添加失败!");
    console.error(error);
  }
};

// 页面加载时获取车辆数据（编辑时）
onMounted(() => {
  fetchVehicleData();
});
</script>

<style scoped>
.container {
  background-color: white;
  height: auto;
  margin-top: 2rem;
  margin-bottom: 2rem;
}

h1 {
  font-size: 2rem;
  font-weight: 600;
  padding: 2rem 0 10px 4rem;
}

span {
  display: inline-block;
  font-size: 15px;
  margin: 1rem 2rem 1rem 0;
  line-height: 24px;
  width: 100px;
  text-align: right;
}

.body {
  display: grid;
  justify-content: center;
  align-items: center;
}

.input {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  width: auto;
}

/* 固定左侧宽度 */
.input-left {
  width: 120px; /* 固定宽度，确保文字对齐 */
  text-align: right; /* 文字右对齐 */
}

.input-right {
  width: 300px; /* 右侧部分自适应剩余空间 */
}

.input-righta {
  flex: 1; /* 右侧部分自适应剩余空间 */
}

.upload-area {
  max-width: 400px;
}

::v-deep .el-upload-list {
  display: flex !important;
  flex-wrap: wrap !important;
  gap: 10px !important;
  justify-content: flex-start !important;
  padding: 10px !important;
}

::v-deep .el-upload-list-item {
  max-width: 50px; /* 缩小图片显示的宽度 */
  max-height: 80px; /* 缩小图片显示的高度 */
  overflow: hidden;
  border-radius: 4px; /* 图片圆角 */
}

.el-upload-list-item img {
  width: 100%; /* 图片宽度适应容器 */
  height: 100%; /* 图片高度适应容器 */
  object-fit: cover; /* 图片裁剪，保持内容居中 */
}

.action-buttons {
  display: flex;
  justify-content: flex-start;
  gap: 1rem;
  margin-top: 2rem;
}
</style>
